<template>
  <view class="car-repair-page">
    <!-- 地图容器 - 占据上方2/3区域 -->
    <view class="map-container" id="mapContainer">
      <!-- 附近门店按钮 -->
      <view class="nearby-store-btn" @click="goNearbyStores">
        <text>附近门店></text>
        <view class="btn-arrow">↓</view>
      </view>
    </view>
    
    <!-- 门店信息卡片 - 占据底部1/3区域 -->
    <view class="store-card">
      <view class="store-header">
        <view class="store-name">{{currentStore.name}}</view>
        <text class="store-distance">{{currentStore.distance}}m</text>
      </view>
      
      <!-- 门店切换指示器 -->
      <view class="store-indicator">
        <view 
          class="indicator-dot" 
          :class="{ 'active': currentStore.name === store.name }" 
          v-for="(store, index) in storeList" 
          :key="index"
          @click="switchStore(index)"
        ></view>
      </view>
      
      <view class="store-content">
        <view class="store-info">
          <view class="rating-time-row">
            <view class="store-rating">
              <text class="star filled">★</text>
              <text class="star filled">★</text>
              <text class="star filled">★</text>
              <text class="star">★</text>
              <text class="star">★</text>
            </view>
            <text class="store-time">{{currentStore.time}}</text>
          </view>
          
          <view class="store-details">
            <view class="business-hours">营业时间: {{currentStore.businessHours}}</view>
            <view class="store-address">{{currentStore.address}}</view>
          </view>
        </view>
        
        <view class="store-thumbnail">
          <image src="@/img/车辆维修/维修厂1.jpeg" mode="aspectFill"></image>
        </view>
      </view>
      
      <view class="store-actions">
        <button class="contact-btn" @click="contactStore(currentStore.phone)">联系门店</button>
        <button class="book-btn" @click="bookStore(currentStore)">立即预定</button>
      </view>
    </view>
    
    <!-- 自定义电话弹窗 - 与原型图完全一致 -->
    <view class="phone-dialog-overlay" v-if="showPhoneDialog" @click="closePhoneDialog">
      <view class="phone-dialog" @click.stop>
        <view class="phone-number">{{currentStore.phone}}</view>
        <button class="call-btn" @click="makePhoneCall">呼叫</button>
        <button class="cancel-btn" @click="closePhoneDialog">取消</button>
      </view>
    </view>
  </view>
</template>

<script>
// #ifdef H5
import AMapLoader from '@amap/amap-jsapi-loader';
// #endif

// #ifdef MP-WEIXIN
import amap from '@/common/amap-wx.js';
// #endif

export default {
  data() {
    return {
      showPhoneDialog: false, // 控制自定义电话弹窗显示
      currentStore: {
        name: "伟业汽车维修厂(人民路店)",
        time: "3分",
        distance: "44m",
        rating: 3,
        businessHours: "周一至周五 09:00-22:00",
        address: "山阳区人民中路32号",
        phone: "18893029302",
        longitude: 113.2145,
        latitude: 35.2478,
        image: require("@/img/车辆维修/维修厂1.jpeg")
      },
      storeList: [
        {
          name: "伟业汽车维修厂(人民路店)",
          distance: 44,
          time: "3分",
          rating: 3,
          businessHours: "周一至周五 09:00-22:00",
          address: "山阳区人民中路32号",
          phone: "18893029302",
          longitude: 113.2145,
          latitude: 35.2478,
          image: require("@/img/车辆维修/维修厂1.jpeg")
        },
        {
          name: "速修汽车服务中心",
          distance: 890,
          time: "8分",
          rating: 4.5,
          businessHours: "周一至周日 07:30-22:00",
          address: "解放区塔南路158号",
          phone: "18893029303",
          longitude: 113.2256,
          latitude: 35.2512,
          image: require("@/img/车辆维修/维修厂1.jpeg")
        }
      ],
      map: null,
      amapKey: '8477719e461b7195529912991c106c9a',
      longitude: 113.2145,       // 修改为门店经度
      latitude: 35.2478,         // 修改为门店纬度
      markers: [{
        longitude: 113.2145,  
        latitude: 35.2478,
        title: "伟业汽车维修厂(人民路店)" 
      },
      {
        longitude: 113.2256, 
        latitude: 35.2512, 
        title: "速修汽车服务中心" 
      }]
    };
  },
  
  onReady() {
    this.initMap();
  },
  
  methods: {
    initMap() {
      // #ifdef H5
      AMapLoader.load({
        key: this.amapKey,
        version: '2.0',
        plugins: ['AMap.Marker', 'AMap.Geolocation']
      }).then((AMap) => {
        this.map = new AMap.Map('mapContainer', {
          zoom: 16,              // 增加缩放级别，更近距离显示
          center: [this.longitude, this.latitude]
        });
        
        this.addStoreMarkers(AMap);
        
        this.map.plugin('AMap.Geolocation', () => {
          const geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,
            timeout: 10000
          });
          this.map.addControl(geolocation);
          geolocation.getCurrentPosition((status, result) => {
            if (status === 'complete') {
              this.longitude = result.position.lng;
              this.latitude = result.position.lat;
              this.map.setCenter([this.longitude, this.latitude]);
            }
          });
        });
      }).catch(e => {
        console.error('H5地图加载失败:', e);
      });
      // #endif
      
      // #ifdef MP-WEIXIN
      const amapPlugin = new amap.AMapWX({ key:'8477719e461b7195529912991c106c9a'});
      
      amapPlugin.getRegeo({
        success: (data) => {
          this.longitude = data[0].longitude;
          this.latitude = data[0].latitude;
          this.addStoreMarkers();
        },
        fail: (err) => {
          console.error('小程序定位失败:', err);
        }
      });
      // #endif
    },
    
    addStoreMarkers(AMap) {
      // #ifdef H5
      this.storeList.forEach((store, index) => {
        const marker = new AMap.Marker({
          position: [store.longitude, store.latitude],
          title: store.name,
          label: {
            content: store.name,
            offset: new AMap.Pixel(0, 30)
          }
        });
        marker.setMap(this.map);
      });
      // #endif
      
      // #ifdef MP-WEIXIN
      this.markers = this.storeList.map((store, index) => ({
        id: index,
        longitude: store.longitude,
        latitude: store.latitude,
        title: store.name,
        iconPath: '/static/marker.png',
        width: 30,
        height: 30
      }));
      // #endif
    },
    
    goNearbyStores() {
      uni.navigateTo({
        url: "/pages/nearbyStores/nearbyStores",
        success: () => {
          console.log('跳转到附近门店页面成功');
        },
        fail: (err) => {
          console.error('跳转到附近门店页面失败：', err);
        }
      });
    },
    
    contactStore(phoneNumber) {
      console.log('联系门店，电话号码:', phoneNumber);
      
      const formattedPhone = phoneNumber.replace(/[^\d-]/g, '');
      if (!formattedPhone) {
        uni.showToast({ title: '电话号码格式错误', icon: 'none' });
        return;
      }
    
      // 显示自定义电话弹窗，避免系统默认的重复取消按钮
      this.showPhoneDialog = true;
    },
    
    // 关闭电话弹窗
    closePhoneDialog() {
      this.showPhoneDialog = false;
    },
    
    // 拨打电话
    makePhoneCall() {
      const formattedPhone = this.currentStore.phone.replace(/[^\d-]/g, '');
      console.log('开始拨打电话:', formattedPhone);
      
      uni.makePhoneCall({
        phoneNumber: formattedPhone,
        success: () => {
          console.log('拨打电话成功');
          this.closePhoneDialog();
        },
        fail: (err) => {
          console.error('拨打电话失败：', err);
          uni.showToast({ 
            title: '拨打电话失败', 
            icon: 'none' 
          });
        }
      });
    },
    
    bookStore(store) {
      console.log('准备跳转到门店详情页面，门店数据:', store);
      
      // 跳转到门店详情页面，传递门店数据
      uni.navigateTo({
        url: `/pages/storeDetails/storeDetails?storeData=${encodeURIComponent(JSON.stringify(store))}`,
        success: () => {
          console.log('跳转到门店详情页面成功');
        },
        fail: (err) => {
          console.error('跳转到门店详情页面失败：', err);
          uni.showToast({
            title: '页面跳转失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 切换当前门店
    switchStore(storeIndex) {
      if (this.storeList[storeIndex]) {
        this.currentStore = { ...this.storeList[storeIndex] };
        console.log('切换到门店:', this.currentStore.name);
      }
    }
  }
};
</script>

<style scoped>
.car-repair-page {
  width: 100%;
  height: 100vh;
  background-color: #f5f5f5;
  position: relative;
}

/* 地图容器样式 - 占据上方2/3区域 */
.map-container {
  width: 100%;
  height: calc(100vh - 200rpx);
  background-color: #e8e8e8;
  position: relative;
}

/* 附近门店按钮样式 */
.nearby-store-btn {
  position: absolute;
  top: 50%;
  right: 30rpx;
  background-color: #666;
  color: #fff;
  padding: 20rpx 30rpx;
  border-radius: 20rpx;
  font-size: 28rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 10;
}

.btn-arrow {
  font-size: 24rpx;
  margin-top: 10rpx;
  color: #007AFF;
}

/* 门店信息卡片样式 - 占据底部1/3区域 */
.store-card {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-radius: 30rpx 30rpx 0 0;
  padding: 40rpx 30rpx 30rpx;
  box-shadow: 0 -4rpx 20rpx rgba(0,0,0,0.1);
  display: flex;
  flex-direction: column;
  position: relative;
}

.store-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.store-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  line-height: 1.2;
}

.store-distance {
  font-size: 28rpx;
  color: #007AFF;
  font-weight: bold;
}

.store-indicator {
  display: flex;
  justify-content: center;
  gap: 10rpx;
  margin: 15rpx 0;
}

.indicator-dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  background-color: #ddd;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.indicator-dot.active {
  background-color: #007AFF;
}

.store-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 25rpx;
}

.store-info {
  flex: 1;
  margin-right: 25rpx;
}

.rating-time-row {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
}

.store-rating {
  display: flex;
  align-items: center;
  margin-right: 12rpx;
}

.star {
  font-size: 26rpx;
  color: #ddd;
  margin-right: 3rpx;
}

.star.filled {
  color: #FFD700;
}

.store-time {
  font-size: 26rpx;
  color: #333;
  font-weight: normal;
}

.store-details {
  display: flex;
  flex-direction: column;
}

.business-hours {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.store-address {
  font-size: 26rpx;
  color: #666;
  line-height: 1.4;
}

/* 门店缩略图 */
.store-thumbnail {
  width: 100rpx;
  height: 120rpx;
  border-radius: 8rpx;
  overflow: hidden;
  flex-shrink: 0;
  margin-top: 5rpx;
}

.store-thumbnail image {
  width: 100%;
  height: 100%;
}

.store-actions {
  display: flex;
  gap: 15rpx;
  margin-bottom: 0;
}

.contact-btn, .book-btn {
  flex: 1;
  height: 75rpx;
  border-radius: 35rpx;
  font-size: 28rpx;
  border: none;
}

.contact-btn {
  background-color: #f0f2f5;
  color: #333;
}

.book-btn {
  background-color: #ff4757;
  color: #fff;
}

/* 自定义电话弹窗样式 - 与原型图完全一致 */
.phone-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  z-index: 1000;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}

.phone-dialog {
  width: 100%;
  background-color: #fff;
  border-radius: 16rpx 16rpx 0 0;
  overflow: hidden;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.phone-number {
  text-align: center;
  font-size: 28rpx;
  color: #333;
  padding: 40rpx 30rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #e5e5e5;
}

.call-btn, .cancel-btn {
  height: 110rpx;
  font-size: 28rpx;
  border: none;
  width: 100%;
  background-color: #fff;
  color: #333;
  border-bottom: 1rpx solid #e5e5e5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cancel-btn {
  border-bottom: none;
}

.call-btn:active, .cancel-btn:active {
  background-color: #f5f5f5;
}
</style>
